package com.etalk.crm.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.etalk.crm.dao.AchievementManagementMapper;
import com.etalk.crm.dao.PersonMapper;
import com.etalk.crm.dao.StudentInfoMapper;
import com.etalk.crm.pojo.*;
import com.etalk.crm.service.StudentInfoService;
import com.etalk.crm.utils.EncryptAndDecrypt;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Jordan
 * @date: 2019/1/3 19:12
 * @description:
 */
@Service
public class StudentInfoServiceImpl implements StudentInfoService {
    private static final Logger logger= LogManager.getLogger(StudentInfoServiceImpl.class);

    @Resource
    private PersonMapper personMapper;
    @Resource
    private StudentInfoMapper studentInfoMapper;
    @Resource
    private AchievementManagementMapper achievementManagementMapper;
    @Resource
    private HttpSession session;

    /**
     * 查询学员信息卡数据
     * @param personId 学员id
     * @return 学员信息
     */
    @Override
    public StudentInfo searchStudentInfo(Integer personId){
        StudentInfo result = personMapper.selectStudentInfoByPersonId(personId);
        //生成tokenString
        Map<String, Object> datamap=new HashMap<>(6);
        datamap.put("loginId", result.getPersonId());
        datamap.put("loginName", result.getLoginName());
        datamap.put("roleId", 3);
        datamap.put("storeId",result.getStoresId());
        result.setTokenString(EncryptAndDecrypt.encrypt(JSON.toJSONString(datamap)));
        List<Map<String,Object>> weixinList=personMapper.selectWeixinByPersonId(personId);
        result.setBindingWeixin(weixinList.size()>0);
        result.setListWeixin(weixinList);
        List<Map<String,Object>> appList=personMapper.selectAppOnlineByPersonId(personId);
        result.setBindingApp(appList.size()>0);
        result.setListApp(appList);
        return result;
    }

    /**
     * 生成用户token String
     * @param personId 用户id
     * @return
     */
    @Override
    public String getStudentTokenString(int personId){
        StudentInfo result = personMapper.selectTokenStringInfoById(personId);
        if (result==null || result.getPersonId()==null){
            return "";
        }
        Map<String, Object> datamap=new HashMap<>(6);
        datamap.put("loginId", result.getPersonId());
        datamap.put("loginName", result.getLoginName());
        datamap.put("roleId", result.getRoleId());
        datamap.put("storeId",result.getStoresId());
        return EncryptAndDecrypt.encrypt(JSON.toJSONString(datamap));
    }

    /**
     * 查询学员信息变更记录
     * @param personId 学员id
     * @param pageNum 页码
     * @param pageSize 每页记录
     * @return 数据对象
     */
    @Override
    public PageInfo<StudentChangeRecord> searchStudentChangRecordByPage(Integer personId,int pageNum,int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<StudentChangeRecord> list=personMapper.selectStudentChangeRecord(personId);
        return new PageInfo<>(list);
    }

    /**
     * 查询et问题监控用户列表
     * @param searchKey 查询关键字
     * @param pageNum 当前页
     * @param pageSize 每页记录数
     * @return 列表
     */
    @Override
    public PageInfo<EtMonitoringList> searchEtMonitoringListByPage(String searchKey,int pageNum,int pageSize){

        PageHelper.startPage(pageNum,pageSize);
        List<EtMonitoringList> list=studentInfoMapper.selectMonitorList(searchKey);
        return new PageInfo<>(list);
    }

    /**
     * 添加问题用户记录
     * @param personId 用户id
     * @param content 问题内容
     * @return 记录数
     */
    @Override
    public int addEtMonitorPerson(int personId,String content){
        int num=0;
        try {
            num = studentInfoMapper.insetMonitorInfo(personId,content,session.getAttribute("loginname").toString());
        }catch (Exception e){
            if(e instanceof DuplicateKeyException) {
                num = -1;
            }
            logger.error("添加问题用户监控出错："+e.getMessage(),e);
        }
        return num;
    }

    /**
     * 修改监控内容
     * @param personId 用户id
     * @param content 监控内容
     * @return 记录数
     */
    @Override
    public int updateEtMonitorPersonByContent(int personId,String content){
        return studentInfoMapper.updateMonitorContentByPersonId(personId,content,session.getAttribute("loginname").toString());
    }

    /**
     * 修改监控状态
     * @param personId 用户id
     * @param state 是否启用监控：0否，1是
     * @return 记录数
     */
    @Override
    public int updateEtMonitorPersonByState(int personId,int state){
        return studentInfoMapper.updateMonitorStateByPersonId(personId,state,session.getAttribute("loginname").toString());
    }

    /**
     * 删除监控记录
     * @param personId 用户id
     * @return 记录数
     */
    @Override
    public int delEtMonitorInfoByPersonId(int personId){
        return studentInfoMapper.deleteMonitorRecordByPersonId(personId);
    }

    /**
     * 查询学员老师信息
     * @param loginName 查询关键字
     * @return 用户信息
     */
    @Override
    public List<Person> searchPersonListBySearchKey(String loginName) {
        return studentInfoMapper.selectPersonList(loginName);
    }

    /**
     * 查询有效的性格数据列表
     * @return
     */
    @Override
    public List<DispositionResult> searchDispositionList(Integer personId){
        if (personId==null){
            personId=0;
        }
        return studentInfoMapper.selectDispositionList(personId);
    }

    /**
     * 成绩变化曲线图数据(学校收集成绩，期中期末考试成绩，单元测成绩，课后练习成绩)
     * @param personId 学员id
     * @return
     */
    @Override
    public Map<String,Object> searchAchievementInfo(Integer personId){
        Map<String,Object> resultMap=new HashMap<>(8);

        List<String> listName = new ArrayList<>();
        List<BigDecimal> listScore=new ArrayList<>();
        //学校成绩
        List<SchoolGradesResultMap> list=achievementManagementMapper.selectSchoolGradesList(personId);
        if (list!=null && list.size()>0){
            for (SchoolGradesResultMap record:list){
                listName.add(record.getYear()+"/"+record.getGrade()+"\n"+record.getSchoolTerm()+"/"+record.getTestName());
                listScore.add(record.getScore());
            }
        }
        resultMap.put("schoolName",listName);
        resultMap.put("schoolScore",listScore);

        //Etalk期中、期末成绩
        listName = new ArrayList<>();
        listScore=new ArrayList<>();
        list=achievementManagementMapper.selectEtalkGradesList(personId);
        if (list!=null && list.size()>0){
            for (SchoolGradesResultMap record:list){
                listName.add(record.getYear()+"/"+record.getGrade()+"\n"+record.getSchoolTerm()+"/"+record.getTestName());
                listScore.add(record.getScore());
            }
        }
        resultMap.put("etalkName",listName);
        resultMap.put("etalkScore",listScore);

        //Etalk单元测成绩
        listName = new ArrayList<>();
        listScore=new ArrayList<>();
        list=achievementManagementMapper.selectUnitGradesList(personId);
        if (list!=null && list.size()>0){
            for (SchoolGradesResultMap record:list){
                listName.add(record.getYear()+"/"+record.getGrade()+"\n"+record.getSchoolTerm()+"/"+record.getTestName());
                listScore.add(record.getScore());
            }
        }
        resultMap.put("unitName",listName);
        resultMap.put("unitScore",listScore);

        //Etalk课后练习
        listName = new ArrayList<>();
        listScore=new ArrayList<>();
        list=achievementManagementMapper.selectHomeworkGradesList(personId);
        if (list!=null && list.size()>0){
            for (SchoolGradesResultMap record:list){
                listName.add(record.getTestName());
                listScore.add(record.getScore());
            }
        }
        resultMap.put("homeworkName",listName);
        resultMap.put("homeworkScore",listScore);

        //老师对学员上课态度和学术表现月平均得分
        listName = new ArrayList<>();
        List<BigDecimal> listParticipation=new ArrayList<>();
        List<BigDecimal> listConcentration=new ArrayList<>();
        List<BigDecimal> listListening=new ArrayList<>();
        List<BigDecimal> listPronunciation=new ArrayList<>();
        List<BigDecimal> listVocabulary=new ArrayList<>();
        List<BigDecimal> listGrammar=new ArrayList<>();
        List<BigDecimal> listSpoken=new ArrayList<>();
        List<AcademicPerformanceResultMap> list1=achievementManagementMapper.selectAcademicPerformanceList(personId);
        if (list1!=null && list1.size()>0){
            for (AcademicPerformanceResultMap record:list1){
                listName.add(record.getYearMonth());
                listParticipation.add(record.getParticipationAve());
                listConcentration.add(record.getConcentrationAve());
                listListening.add(record.getListenAve());
                listPronunciation.add(record.getPronunciationAve());
                listVocabulary.add(record.getVocabularyAve());
                listGrammar.add(record.getGrammarAve());
                listSpoken.add(record.getSpokenAve());
            }
        }
        resultMap.put("studyName",listName);
        resultMap.put("listParticipation",listParticipation);
        resultMap.put("listConcentration",listConcentration);
        resultMap.put("listListening",listListening);
        resultMap.put("listPronunciation",listPronunciation);
        resultMap.put("listVocabulary",listVocabulary);
        resultMap.put("listGrammar",listGrammar);
        resultMap.put("listSpoken",listSpoken);

        return resultMap;
    }

}
